const generateFile = require('../utils/generateFile ');
const walk = require('walk')

const renderEntRouterFile = async (location) => {
    console.log('--cur render server entity router --');
    return new Promise(async (resolve, reject) => {
        const tempFileContent = await createContentTemp(location);
        const { code } = await generateFile(`dist/route/entity.js`, tempFileContent);
        if(code === 1) resolve({ code: 1, data: 'render entity router successfully !'})
        else reject({ code : -1, data: 'render entity router error !'});
    })
}

const createContentTemp = async (location) => {
    let entityList = await getFileList(location)
    console.log(entityList);
    // const user = require('../entity/user')
    if(!Array.isArray(entityList)) return new Error('input tbEntity must be Array !');
    let entityCont = `const express = require('express')
        const router = express.Router()
        
        module.exports = router
        
        // entity import
        ${createImportTemp(entityList)}
        
        // entity interceptors
        router.use((req, res, next) => {
            next();
        })
        
        ${createRouterTemp(entityList)}`
    return Promise.resolve(entityCont);
}


const getFileList = (location) => {
    let files = [];
    return new Promise((resolve) => {
        let walker  = walk.walk(location, { followLinks: false });
        walker.on('file', (roots, stat, next) => {
            files.push(stat.name.split('.').shift().toString());
            next();
        });
        walker.on('end', () => {
            resolve(files)
        });
    })
}

const createImportTemp = (entityList) => {
    let strArr = [];
    for (const item of entityList) {
        let str = `const ${item} = require('../entity/${item}')`
        strArr.push(str);
    }
    return strArr.join('\n').toString();
}

const createRouterTemp = (entityList) => {
    let strArr = [];
    for (const item of entityList) {
        let str = `// ${item}
        router.use('/${item}', (req, res) => {
            const { url } = req;
            if(url === '/findAndCountAll') ${item}.findAndCountAll(req, res);
            if(url === '/findById') ${item}.findById(req, res);
            if(url === '/create') ${item}.create(req, res);
            if(url === '/deleteById') ${item}.deleteById(req, res);
            if(url === '/updateById') ${item}.updateById(req, res);
        });`
        strArr.push(str);
    }
    return strArr.join('\n').toString();
}

module.exports = renderEntRouterFile